//
//  ST_ReportDetailController.swift
//  btvideo
//
//  Created by mac on 2019/12/5.
//  Copyright © 2019 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import TZImagePickerController

class ST_ReportDetailController: ST_BTLightBarViewController{

    override func viewDidLoad() {
        super.viewDidLoad()
        
        title_nav_btn.setTitleForAllStates("举报")
        
        view.backgroundColor = Color.white
        view.addSubview(inputBoxView)
        inputBoxView.snp.makeConstraints { (make) in
            make.top.equalTo(own_navigation_bar.snp.bottom).offset(5)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(160)
        }
        
        inputBoxView.addSubview(textView)
        textView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 20, left: 20, bottom: 40, right: 45))
        }
        
        
        
        inputBoxView.addSubview(countLabel)
        countLabel.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.top.equalTo(textView.snp.bottom).offset(10)
        }
        
        inputBoxView.addSubview(placeholderLabel)
        placeholderLabel.snp.makeConstraints { (make) in
            make.left.equalTo(textView).offset(5)
            make.top.equalTo(textView).offset(7)
            make.right.equalTo(textView).offset(-5)
        }
        
        
        view.addSubview(titleLabel1)
        view.addSubview(titleLabel2)
        
        titleLabel1.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalTo(inputBoxView.snp.bottom).offset(30)
        }
        
        titleLabel2.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalTo(titleLabel1.snp.bottom).offset(15)
        }
        
        view.addSubview(btn1)
        view.addSubview(btn2)
        view.addSubview(btn3)
        
        btn1.snp.makeConstraints { (make) in
            make.width.height.equalTo(70)
            make.top.equalTo(titleLabel2.snp.bottom).offset(20)
            make.left.equalToSuperview().offset(15)
        }
        
        
        btn2.snp.makeConstraints { (make) in
            make.width.height.equalTo(btn1)
            make.top.equalTo(titleLabel2.snp.bottom).offset(20)
            make.left.equalTo(btn1.snp.right).offset(15)
        }
        
        btn3.snp.makeConstraints { (make) in
            make.width.height.equalTo(70)
            make.top.equalTo(titleLabel2.snp.bottom).offset(20)
            make.left.equalTo(btn2.snp.right).offset(15)
        }
        
        
        view.addSubview(pushReportBtn)
        pushReportBtn.snp.makeConstraints { (make) in
            make.width.equalTo(280)
            make.height.equalTo(40)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-49)
        }
    }
    

    
//    MARK: - Properties
    var target_accid = ""
    var comments = ""
    
    var video_id:String?
    
    
    fileprivate lazy var inputBoxView:UIView = {
        let control = UIView()
        control.backgroundColor = Color.init(hex: 0xF2F4F7)
        control.cornerRadius = 8
        return control
    }()
    
    

    
    fileprivate lazy var titleLabel1:UILabel = {
        let control = UILabel()
        let attrString = NSMutableAttributedString(string: "上传截图，提高举报准确度")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.attributedText = attrString
        return control
    }()
        
    fileprivate lazy var titleLabel2:UILabel = {
        
        let control = UILabel()
        
       let attrString = NSMutableAttributedString(string: "(鼓励上传微信等其他平台聊天记录截图)")
 
       let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        
       attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
       
       let strSubAttr1: [NSMutableAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2,alpha:1)]
       attrString.addAttributes(strSubAttr1, range: NSRange(location: 0, length: 5))

       let strSubAttr2: [NSMutableAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 1, green: 0.12, blue: 0.34,alpha:1)]
       attrString.addAttributes(strSubAttr2, range: NSRange(location: 5, length: 2))

       let strSubAttr3: [NSMutableAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2,alpha:1)]
       attrString.addAttributes(strSubAttr3, range: NSRange(location: 7, length: 12))
        
        control.attributedText = attrString
        return control
    }()
    
    fileprivate lazy var textView:UITextView = {
       let control = UITextView()
        control.textColor = Color.init(hex: 0x333333)
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.delegate = self
        control.tintColor = Color.init(hex: 0x333333)
        control.backgroundColor = Color.clear
        return control
    }()
    
    fileprivate lazy var placeholderLabel:UILabel = {
       let control = UILabel()
        control.textColor = Color.init(hex: 0x999999)
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.numberOfLines = 0
        control.text = "请写下少于10字的举报理由（非必填）"
        return control
    }()
    
    fileprivate lazy var countLabel:UILabel = {
        let control = UILabel()
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.semibold)
        control.textColor = UIColor.init(hex: 0x999999)
        control.textAlignment = .right
//        control.backgroundColor = Color.random
        return control
    }()
    fileprivate let btnBaseTag = 1028
    
    fileprivate lazy var btn1:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("个人中心_img_举报_添加图片")!)
        control.setImage(nil, for: UIControl.State.highlighted)
        control.imageView?.contentMode = UIView.ContentMode.scaleAspectFill
        control.cornerRadius = 6
        control.isHidden = false
        control.tag = btnBaseTag
        control.add_touch_up(insideTarget: self, action: #selector(addImageHandle(sender:)))
        return control
        
    }()
    
    fileprivate lazy var btn2:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("个人中心_img_举报_添加图片")!)
        control.setImage(nil, for: UIControl.State.highlighted)
        control.imageView?.contentMode = UIView.ContentMode.scaleAspectFill
        control.cornerRadius = 6
        control.isHidden = true
        control.tag = btnBaseTag + 1
        control.add_touch_up(insideTarget: self, action: #selector(addImageHandle(sender:)))
        return control
        
    }()
    
    fileprivate lazy var btn3:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("个人中心_img_举报_添加图片")!)
        control.setImage(nil, for: UIControl.State.highlighted)
        control.imageView?.contentMode = UIView.ContentMode.scaleAspectFill
        control.cornerRadius = 6
        control.isHidden = true
        control.tag = btnBaseTag + 2
        control.add_touch_up(insideTarget: self, action: #selector(addImageHandle(sender:)))
        return control
        
    }()
    
    
    fileprivate lazy var pushReportBtn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = Color.init(hex: 0xFEC207)
        control.cornerRadius = 40/2.0
        control.setTitleForAllStates("提交")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.addTarget(self, action: #selector(pushReportHandle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate var selectImages = [Int:UIImage]()
    
    
    
    
    fileprivate var uploadSuccessKeys = [String]()
    
    
}

//MARK: - Event
extension ST_ReportDetailController:UITextViewDelegate,TZImagePickerControllerDelegate{
    
    func textViewDidChange(_ textView: UITextView) {
        placeholderLabel.isHidden = !textView.text.isEmpty
    }
    
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        let mutableStr = NSMutableString.init(string: textView.text)
        
        mutableStr.replaceCharacters(in: range, with: text)
        
        countLabel.text = String.init(format: "%d/50", mutableStr.length)
        
        countLabel.textColor = mutableStr.length > 50 ? UIColor.init(hexString: "#FF1F56") : UIColor.init(hexString: "#999999")
        
        if mutableStr.length > 60{
            return false
        }
        
        return true
        
    }
    
    @objc func addImageHandle(sender:UIButton){
        
        if let vc = TZImagePickerController.init(maxImagesCount: 1, delegate: self){
            vc.allowPickingVideo = false
            vc.didFinishPickingPhotosHandle = {[weak self] photos,assets,isSelectOriginalPhoto in
                
                if let image = photos?.first{
                    
                    sender.setImage(image, for: UIControl.State.selected)
                    sender.isSelected = true
                    
                    if sender.tag - 1028 == 0{
                        self?.btn2.isHidden = false
                        self?.selectImages.updateValue(image, forKey: 0)
                    }else if sender.tag - 1028 == 1{
                        self?.btn3.isHidden = false
                        self?.selectImages.updateValue(image, forKey: 1)
                    }else{
                        self?.selectImages.updateValue(image, forKey: 2)
                    }
                    
                }
            }
            GlobalPresent(toController: vc, animated: true)
        }
    }
    
    func uploadImages(){
        
        if let uploadImage = selectImages.removeValueForRandomKey(),let data = uploadImage.pngData(){
            
            let fileKey = UUID().uuidString
            
            JVUpload(fileKey: fileKey, data: data, uploadProgress: { (f) in
                
            }, success: { (json) in
                
                self.uploadSuccessKeys.append(fileKey)
                
                self.uploadImages()
                
            }) { (code, error) in
                
                ToastHud(text: error, view: self.view)
            }
            
        }else{
            
            pushRequest()
        }
    }
    
    
    func pushRequest(){
        
        var param = ["target_accid":target_accid,"comments":comments]
                
//        默认举报用户
        var api = PH.reportUserApi
        
        if let vId = video_id{
            api = PH.reportVideoApi
            param.updateValue(vId, forKey: "video_id")
        }
        
        if let remark = textView.text{
            param.updateValue(remark, forKey: "remark")
        }
        
        if self.uploadSuccessKeys.count > 0{
            param.updateValue(self.uploadSuccessKeys.joined(separator: ","), forKey: "proof_img")
        }
        
        JVrequest(api,parameters:param ,success: { (json) in
            
            ToastHud(text: "已成功举报，你将不会再看到此用户", view: self.view)
            
            main_thread_execute(afterDelay: 1.6) {
                
                self.navigationController?.dismiss(animated: true, completion: {
                    
                })
            }
            
        }) { (code, error) in
            ToastHud(text: error, view: self.view)
        }
        
        
    }
    
    @objc func pushReportHandle(){
        
        if let remark = textView.text,remark.count > 50{
            ToastHud(text: "举报理由需少于50个字", view: self.view)
            return
        }
        
        
        self.uploadSuccessKeys.removeAll()
        
        self.show_indeterminate_h_u_d()
        
        self.uploadImages()
        
        
        
    }
    
    
}
